#!/usr/bin/env bash
set -euo pipefail

ROOT="$(cd "$(dirname "$0")/.." && pwd)"
DATE_TAG="$(date +%Y%m%d)"
# 优先以 compose 中的 image 标签为准，其次使用当天日期；也可外部覆盖 TAG
if [ -z "${TAG:-}" ]; then
  if COMPOSE_TAG_LINE=$(grep -E "^\s*image:\s*danciyixue-boot:" -n "$ROOT/deploy/docker-compose.yml" | head -n1); then
    COMPOSE_TAG=$(printf "%s" "$COMPOSE_TAG_LINE" | sed -E 's/.*image:\s*danciyixue-boot:([^[:space:]]+).*/\1/')
    TAG="$COMPOSE_TAG"
  else
    TAG="prod-${DATE_TAG}"
  fi
fi

echo "[1/4] 构建后端镜像 danciyixue-boot:${TAG} ..."
# 使用 deploy/dockerfile 与预先构建的 JAR，更贴合离线交付流程
# 注意：Docker build 上下文需为 deploy，使得 COPY danciyixue-boot.jar 能找到文件
test -f "$ROOT/deploy/danciyixue-boot.jar" || { echo "错误: 未找到 $ROOT/deploy/danciyixue-boot.jar，请先放置构建产物" >&2; exit 1; }
docker build -f "$ROOT/deploy/dockerfile" -t danciyixue-boot:"$TAG" "$ROOT/deploy"

echo "[2/4] 准备第三方镜像 ..."
ensure_image() {
  local image="$1"
  if [ "${SKIP_PULL:-0}" != "1" ]; then
    if ! docker pull "$image" >/dev/null 2>&1; then
      echo "警告: 拉取 $image 失败，尝试使用本地缓存镜像" >&2
    fi
  fi
  docker image inspect "$image" >/dev/null 2>&1 || {
    echo "错误: 本地不存在镜像 $image，且无法拉取。请联网或预先加载后重试。" >&2
    exit 1
  }
}

ensure_image mysql:8.0.29
ensure_image redis:7.2.3
ensure_image minio/minio:RELEASE.2023-03-20T20-16-18Z
ensure_image xuxueli/xxl-job-admin:2.4.0

echo "[3/4] 导出镜像为 tar ..."
mkdir -p "$ROOT/deploy/images"
docker save -o "$ROOT/deploy/images/danciyixue-boot_${TAG}.tar" danciyixue-boot:"$TAG"
docker save -o "$ROOT/deploy/images/mysql_8.0.29.tar" mysql:8.0.29
docker save -o "$ROOT/deploy/images/redis_7.2.3.tar" redis:7.2.3
docker save -o "$ROOT/deploy/images/minio_RELEASE.2023-03-20T20-16-18Z.tar" minio/minio:RELEASE.2023-03-20T20-16-18Z
docker save -o "$ROOT/deploy/images/xxl-job-admin_2.4.0.tar" xuxueli/xxl-job-admin:2.4.0

echo "[4/4] 生成校验文件 ..."
( cd "$ROOT/deploy/images" && sha256sum *.tar > SHA256SUMS )
echo "镜像导出完成：$ROOT/deploy/images"
